import { Component } from 'react';
import { Boxs, Button, Group, SearchBar, Datetime } from 'saltui';
const { IconButton } = Button;
const {HBox, Box, VBox } = Boxs;
import MyTabBar from 'components/tab_bar';
import MeetingBoardRoom from './MeetingBoardRoom.js';
import DB from '../../../app/db';
import './PageHome.less';
import { nodataIcon } from '../../../app/variables';

Date.prototype.format = function (fmt) { 
  var o = {    
    "M+": this.getMonth() + 1, //月份     
    "d+": this.getDate(), //日     
    "H+": this.getHours(), //小时     
    "m+": this.getMinutes(), //分     
    "s+": this.getSeconds(), //秒     
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度     
    "S": this.getMilliseconds() //毫秒     
  };    
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));    
  for (var k in o)    
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));    
  return fmt;    
}

export default class PageHome extends Component {

 constructor(props) {
    super(props);
    
    //修改待办列表页tab默认值
    document.getElementById("sendTabIndex").value = "0";
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    //是否需要底部tab页
    var hasBottomTab =  document.getElementById("hasBottomTab").value;
    var tabHeight = 0;
    if(hasBottomTab == "1"){
      tabHeight = 56;
    }

    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var winHeight = '';
    if(isAndroid==true){
      winHeight = window.screen.height-52-265-tabHeight+"px";
    }else if(isiOS==true){
      winHeight = window.screen.availHeight-52-265-tabHeight+"px";
    }else {
      if(window.screen.availHeight) {
        winHeight = '500px';
      }
    }
    let currentDate = new Date();
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let activeDate = ymdw.year + '-' + ymdw.month + '-' + ymdw.day + '(' + ymdw.week + ")";
    this.state = {
      anum:'0',
      meetingRoomData:[],
      winHeight: winHeight,
      hasBottomTab: hasBottomTab,
      currentDate: currentDate,
      activeDate: activeDate,
      dateValue: currentDate.getTime(),
      search:''
    };

    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    var isHelpNew = 1;
    dd.util.domainStorage.getItem({ //帮助按钮
       name:'meeting_helpNew_'+userId , // 存储信息的key值
       onSuccess : function(info) {
            var helpNew = info.value;
            if( typeof(helpNew) == 'undefined' || helpNew == '' ){
              isHelpNew = 2;
            }
            //初始化按钮
            t.initButton(isHelpNew);
       },
       onFail : function(err) {
            //alert(JSON.stringify(err));
       }
    });
  }

  //初始化按钮
  initButton(isHelpNew){
    //设置帮助
    /*dd.biz.navigation.setIcon({
        showIcon : true,//是否显示icon
        iconIndex : isHelpNew,//显示的iconIndex,如上图
        onSuccess : function(result) {
            location.hash='help/help_index';
        },
        onFail : function(err) {
        //jsapi调用失败将会回调此函数
        }
    });*/
  }

  componentDidMount(){
    let t = this;
    // if (t.state.anum == '0') {
    //   var calendar=document.getElementById("calendar");
    //   var cld=new CalendarMobile({
    //     el: 'box',
    //     value: '', // 默认为new Date();
    //     parentNode: calendar,
    //     fn: function(obj) {
    //         let year = obj.year;
    //         let month = obj.month<10 ? '0'+(obj.month) : obj.month;
    //         let day = obj.day<10 ? '0'+(obj.day) : obj.day;
            
    //         let date = year + '-' + month + '-' + day;
    //         t.getBoardroom(date);
    //     },
    //     prevMonth:function(obj){
    //       console.log(obj)
    //       let year = obj.year;
    //       let month = obj.month<10 ? '0'+(obj.month) : obj.month;
    //       let day = "";
    //       var currentDate = new Date();
    //       if(year===currentDate.getFullYear() && obj.month===(currentDate.getMonth()+1+"")){
    //         var d = currentDate.getDate();
    //         day = d<10 ? '0'+d : d;
    //       }else{
    //         day = "01";
    //       }
    //       let date = year + '-' + month + '-' + day;
    //       t.getBoardroom(date);
    //     },
    //     nextMonth:function(obj){
    //       console.log(obj)
    //       let year = obj.year;
    //       let month = obj.month<10 ? '0'+(obj.month) : obj.month;
    //       let day = "";
    //       var currentDate = new Date();
    //       if(year===currentDate.getFullYear() && obj.month===(currentDate.getMonth()+1+"")){
    //         var d = currentDate.getDate();
    //         day = d<10 ? '0'+d : d;
    //       }else{
    //         day = obj.day<10 ? '0'+(obj.day) : obj.day;
    //       }
    //       let date = year + '-' + month + '-' + day;
    //       t.getBoardroom(date);
    //     }
    //   });
    //   this.setState({anum:'1'});
    // } 
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : "会议",//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: "会议",
            icon: '',
            actionmenu: {}
        },
      });
    }

    let date = new Date().format("yyyy-MM-dd");
    this.getBoardroom(date);
  }

  componentDidUpdate(){
    // let t = this;
    // var showAllContent = document.getElementById("showAllContent");  
    // showAllContent.addEventListener('click',function(){  
    //     t.clientHeight();   
    // },false) ;
    // this.clientHeight();
  }

  clientHeight(){
    var height=window.screen.height-calendar.clientHeight-48-48;
    var nodataHeight = document.getElementById("nodataHeight");
    if(nodataHeight != undefined){
      nodataHeight.style.height=height +"px"; 
    }
  }

  // 获取会议室列表
  getBoardroom(date){
    DB.SomeModuleAPI.boardroomSetList({condition:date, boardroomName:this.state.search}).then((content) => {
      this.setState({
        currentDate: date,
        meetingRoomData: content.data
      });
    }).catch((error) => {
    });
  }

  // 新增页面
  addMeeting() {
    location.hash = 'meeting/add';
  }

  handleClickHref(path){
    location.hash = path
  }

  scanQrcode(){
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    let ipPort = getLoginUserInfo().contextPageUrl;
    //第三方标识：DING（钉钉），WX（企业微信），MH（移动门户）
    if(thirdMenuType=='DING'){
      dd.biz.util.scan({
        type: "qrCode" , // type 为 all、qrCode、barCode，默认是all。
        onSuccess: function(data) {
          pageSkipDirectly(ipPort + data.text);
        },
        onFail : function(err) {}
      })
    }else if(thirdMenuType=='WX'){
      wx.scanQRCode({
        desc: 'scanQRCode desc',
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
        success: function(res) {
          pageSkipDirectly(ipPort + res.resultStr);
        },
        error: function(res) {
            if (res.errMsg.indexOf('function_not_exist') > 0) {
                alert('版本过低请升级')
            }
        }
      });
    }else if(thirdMenuType=='MH'){
      !!emp&&emp.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由App处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          pageSkipDirectly(ipPort + res.resultStr);
        }
      });
    }
  }

  addNoRoomMeeting(){
    location.hash = 'meeting/add/2/undefined/undefined/undefined/undefined';
  }

  prevMonth(){
    var currentDate = new Date(this.state.currentDate);
    currentDate.setDate(currentDate.getDate() - 1);
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState ({
      currentDate: currentDate,
      activeDate: activeDate,
      dateValue: currentDate.getTime()
    });
    this.getBoardroom(dateStr);
  }

  nextMonth(){
    var currentDate = new Date(this.state.currentDate);
    currentDate.setDate(currentDate.getDate() + 1);
    let ymdw = this.getYearMonthDayWeek(currentDate);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState ({
      currentDate: currentDate,
      activeDate: activeDate,
      dateValue: currentDate.getTime()
    });
    this.getBoardroom(dateStr);
  }

  onConfirm(value, key){
    let date = new Date(value.value);
    let ymdw = this.getYearMonthDayWeek(date);
    let dateStr = ymdw.year + '-' + ymdw.month + '-' + ymdw.day;
    let activeDate = dateStr + '(' + ymdw.week + ")";
    this.setState({
      currentDate: date,
      dateValue: value,
      activeDate: activeDate
    });
    this.getBoardroom(dateStr);
  }

  getYearMonthDayWeek(date){
    if(date){
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var week = date.getDay();
      var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
      let data = {
        year: year,
        month: month < 10 ? '0' + month : month,
        day: day < 10 ? '0' + day : day,
        week: '星期' + weekArray[week],
      }
      return data;
    }
    return null;
  }

  applyBoardroomList(){
    location.hash="meeting/applyBoardroomList";
  }

  //搜索
  onSearch(value) {
    let t = this;
    this.setState({ 
      search : value
    },()=>{
      t.getBoardroom(t.state.currentDate);
    });
  }

  //退出
  onExit(){
    let t = this;
    t.setState({ 
      search : ''
    },() => {
      t.getBoardroom(t.state.currentDate);
    });
  }

  render() {
    let t = this;
    return (
      <div className="page-meeting">
        <div className="t-PB68">
          {/* <div id="calendar"></div> */}
          <Group.List>
            <HBox vAlign="center">
              <Box flex={1}>
              <SearchBar 
                hasHistory={false} 
                instantSearch={false} 
                placeholder='请输入会议室名称搜索' 
                onSearch={this.onSearch.bind(this)}  
                onExit={this.onExit.bind(this)}>
              </SearchBar>
              </Box>
              <Box className="t-FCddblue t-PR16" onClick={this.applyBoardroomList.bind(this)}>已预定会议室</Box>
            </HBox>
            <HBox vAlign="center" className="dd-t-room-date">
              <Box className="t-FCddblue" onClick={this.prevMonth.bind(this)}>前一天</Box>
              <Box className="data-btn t-FAC t-PT2" onClick={()=> {t.dateSlot.show()}}>
                {t.state.activeDate}
                {/*<i className="iconfont icon-calendar-set t-ML6" style={{ fontSize: 16 }}></i>*/}
              </Box>
              <Box className="t-FCddblue" onClick={this.nextMonth.bind(this)}>后一天</Box>
              <Datetime 
                slotRef={s => t.dateSlot = s}
                title="时间选择"
                value={t.state.dateValue}
                columns={Datetime.YMD}
                onConfirm={(value) => { this.onConfirm(value, 'dateValue'); }}
              />
            </HBox>
          </Group.List>
          {/* <Group.List>
            <div className="t-FC3 t-LH44 t-PL16 t-FS16" onClick={this.addNoRoomMeeting.bind(this)}>无需会议室点此发起</div>
          </Group.List> */}
          { this.state.meetingRoomData==null || this.state.meetingRoomData.length<=0 ? 
            <div id="nodataHeight" style={{position: "relative"}}>
              <div className="nodata-wrapper" style={{ marginTop: '100px'}}>
                <VBox vAlign="center" hAlign="center" className="nodata">
                    <Box>
                      <div>
                         <img src={nodataIcon} alt="" style={{width: 68 + 'px'}} />
                       </div>
                    </Box>
                    <Box className="t-FC6">
                        暂无数据
                    </Box>
                </VBox>
              </div>
            </div>
            :
            <MeetingBoardRoom currentDate={this.state.currentDate} meetingData={this.state.meetingRoomData}/>
           }
        </div>
        <MyTabBar activeIndex={2} />
        {/*<div onClick={this.handleClickHref.bind(this,'demo/aboutOne')} style={{bottom:'182', right:'17'}} className="t-animate" ><span className="dd-display">演示</span></div>*/}
        {/* <IconButton className="add-new-page t-BCddblue" onClick={this.scanQrcode.bind(this)} ><i className="iconfont icon-scan t-FCf"></i></IconButton> */}
        {/*<IconButton className="add-new-page t-BCddblue" onClick={this.scanQrcode.bind(this)} style={{bottom:'128px !important'}} ><i className="iconfont icon-scan t-FCf"></i></IconButton>*/}
        {/*<IconButton className="add-new-page t-BCddblue" onClick={this.addMeeting.bind(this)}><i className="iconfont icon-plus t-FCf"></i></IconButton>*/}
      </div>
    );
  }
}


